package com.lib.core.adapter;


import android.annotation.SuppressLint;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;

import java.util.List;

/**
 * 添加notifyDataSetChanged刷新FragmentPage功能,请通过setFragmentPages设置页数据
 */
public class BaseFragmentAdapter extends FragmentPagerAdapter {
    private List<Fragment> fragmentPages;
    private List<String> pageTitles;
    private FragmentManager fragmentManager;

    @SuppressLint("WrongConstant")
    public BaseFragmentAdapter(FragmentManager fm) {
        super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
//        super(fm);
        this.fragmentManager = fm;
    }


    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragmentPages.get(position);
    }

    @Override
    public int getCount() {
        return fragmentPages != null ? fragmentPages.size() : 0;
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }



    public BaseFragmentAdapter setFragmentPages(List<Fragment> fragmentPages) {
        if (this.fragmentPages != null) {
            FragmentTransaction ft = fragmentManager.beginTransaction();
            for (Fragment f : this.fragmentPages) {
                ft.remove(f);
            }
            ft.commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        this.fragmentPages = fragmentPages;
        notifyDataSetChanged();
        return this;
    }

    public BaseFragmentAdapter setPageTitles(List<String> pageTitles) {
        this.pageTitles = pageTitles;
        return this;
    }


    public List<String> getPageTitles() {
        return pageTitles;
    }

    public List<Fragment> getFragmentPages() {
        return fragmentPages;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (pageTitles != null && position < pageTitles.size()) {
            return pageTitles.get(position);
        }
        return super.getPageTitle(position);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        Fragment fragment = (Fragment) object;
        //如果getItemPosition中的值为PagerAdapter.POSITION_NONE，就执行该方法。
        if (fragmentPages.contains(fragment)) {
            super.destroyItem(container, position, fragment);
            return;
        }
        //自己执行移除。因为mFragments在删除的时候就把某个fragment对象移除了，所以一般都得自己移除在fragmentManager中的该对象。
        fragmentManager.beginTransaction().remove(fragment).commitNowAllowingStateLoss();

    }


}
